<template>
  <div class="row-right" @click="conditionShow=false">
    <div class="row">
      <div class="col-xs-12">
        <form class="common-form">
          <div class="form-group row">
            <div class="col-xs-12 col-md-6">
              <label for="">课程名称：</label>
              <input type="text" class="form-control" v-model="cname">
            </div>
            <div class="col-xs-12 col-md-3">
              <label for="">类别：</label>
              <div class="dropdown" :class="{'open':conditionShow}">
                <a @click.stop="conditionShow=true" role="button" data-toggle="dropdown" class="btn btn-default" data-target="javascript:;" href="javascript:;">
                  {{cateName==''?'类别选择':cateName}}
                  <span class="caret"></span>
                </a>
                <ul class="dropdown-menu">
                  <template v-for="oneItem in cateList">
                    <li class="dropdown-submenu" v-if="oneItem.children" :key="oneItem.name">
                      <a href="javascript:;">{{oneItem.name}}</a>
                      <ul class="dropdown-menu">
                        <template v-for="twoItem in oneItem.children">
                          <li class="dropdown-submenu" v-if="twoItem.children" :key="twoItem.name">
                            <a tabindex="-1" href="javascript:;">{{twoItem.name}}</a>
                            <ul class="dropdown-menu">
                              <li v-for="threeItem in twoItem.children" :key="threeItem.name">
                                <a href="javascript:;" @click="handleCateSelect(threeItem.name,oneItem.id,twoItem.id,threeItem.id)">{{threeItem.name}}</a>
                              </li>
                            </ul>
                          </li>
                          <li :key="twoItem.name" v-else>
                            <a href="javascript:;" @click="handleCateSelect(twoItem.name,oneItem.id,twoItem.id)">{{twoItem.name}}</a>
                          </li>
                        </template>
                      </ul>
                    </li>
                    <li :key="oneItem.name" v-else>
                      <a href="javascript:;" @click.stop="handleCateSelect(oneItem.name,oneItem.id)">{{oneItem.name}}</a>
                    </li>
                  </template>
                </ul>
              </div>
            </div>
            <div class="col-xs-12 col-md-3">
              <label for="">总章节：</label>
              <input type="text" class="form-control" v-model="ccount">
            </div>
          </div>
          <div class="form-group row">
            <div class="col-xs-4 col-sm-2">
              <label for="">价格：</label>
              <input type="text" class="form-control" v-model="cprice">
            </div>
            <div class="col-xs-4 col-sm-3">
              <label for="" class="no-label"></label>
              <p class="form-control-static">元 / 套课程</p>
            </div>
            <!-- <label for="" class="col-sm-3 control-label">价格：</label> -->
            <div class="col-xs-4 col-sm-3">
              <label class="radio-inline">
                <input type="radio" value="option1" :checked="cprice==''" @click="cprice=''"> 免费
              </label>

            </div>
          </div>
          <div class="form-group row">
            <div class="col-xs-12 col-md-6">
              <label for="">课程简介：</label>
              <textarea class="form-control" v-model="cdesc" placeholder="最多不超过1000字" style="height:100px"></textarea>
            </div>
            <div class="col-xs-12 col-md-3">
              <label for="">选择封面图：</label>
              <!--<template v-if="cimgUrl">
                <img :src="cimgUrl" alt="" height="100">
                 <p class="form-control-static">{{cimg.name}}</p>
              </template>
              <template v-else> -->
              <a href="javascript:;" class="up-box">
                <img v-if="cimgUrl" :src="cimgUrl" alt="" height="100">
                <img v-else src="../assets/images/icon_add.png" alt="" height="100">
                <input type="file" class="up-input" @change="handleFileChange($event)">
              </a>
              <!-- </template> -->
            </div>
          </div>
          <div class="form-group text-right btn-box">
            <a href="javascript:;" class="btn btn-danger pull-left" v-if="curriculumId">删除课程</a>
            <a href="javascript:;" class="btn-ghost" @click="handleUploadFile($event)">{{addShow&&!curriculumId?'添加':'修改'}}</a>
          </div>
        </form>
        <template v-if="unitShow||curriculumId">
          <div class="clearfix add-unit-btn">
            <a href="javascript:;" class="btn-ghost pull-right" type="button" @click="handleAddUnit()">新建单元</a>
          </div>
          <!-- <div class="clearfix">
                <hr>
            </div> -->
          <div class="unit-item" v-for="(item,index) in unitList" :key="item.id">
            <div class="clearfix">
              <hr>
            </div>
            <div class="form-horizontal">
              <div class="form-group">
                <label for="" class="col-sm-2 control-label">单元名称：</label>
                <div class="col-sm-2">
                  <p class="form-control-static">第{{index+1}}章</p>
                </div>
                <div class="col-sm-5">
                  <input type="text" class="form-control" v-model="item.name">
                </div>
                <div class="col-sm-2 col-sm-offset-1">
                  <button type="button" class="btn btn-default" style="width: 100%" @click="handleUploadUnit($event,index+1)">{{item.id?'修改':'添加'}}</button>
                </div>
              </div>
              <div class="form-group">
                <label for="" class="col-sm-2 control-label">视频：</label>
                <!-- <template v-if="item.addControl||item.videoUrl"> -->
                  <div class="col-sm-3">
                    <p v-if="item.id&&!item.videoInfo.name" class="form-control-static">
                      <a :href="'http://www.kegonghui.com/upload/' +item.videoUrl" target="_blank" class="text-primary">查看视频</a>
                    </p>
                    <a href="javascript:;" class="up-box" v-else>
                      <!-- <button v-if="item.id&&item.videoUrl" class="btn btn-default">修改</button> -->
                      <template>
                        <p v-if="item.videoInfo.name" class="form-control-static">{{item.videoInfo.name}}</p>
                        <img v-else src="../assets/images/icon_add.png" alt="" width="100%">
                      </template>
                      <input type="file" class="up-input" @change="handleFileChange1($event,index)">
                    </a>
                  </div>
                <!-- </template> -->
                <label for="" class="col-sm-2 control-label">附件：</label>
                <div class="col-sm-3">
                  <p v-if="item.id&&item.accessoriesName" class="form-control-static">
                    <a :href="'https://kegonghui.oss-cn-beijing.aliyuncs.com/' + item.accessoriesUrl" target="_blank" class="text-primary">{{item.accessoriesName}}</a>
                  </p>
                  <a href="javascript:;" class="up-box" v-else>
                    <!-- <button v-if="item.id&&item.accessoriesName" class="btn btn-default">修改</button> -->
                    <template>
                      <p v-if="item.accessoriesName" class="form-control-static">{{item.accessoriesName}}</p>
                      <img v-else src="../assets/images/icon_add.png" alt="" width="100%">
                    </template>
                    <input type="file" class="up-input" @change="handleFileChange2($event,index)">
                  </a>
                </div>
                <div class="col-sm-2" v-if="!item.id">
                  <button type="button" class="btn btn-danger" style="width: 100%" @click="handleDeleteUnit(index)">删除</button>
                </div>
              </div>
            </div>
          </div>
        </template>
      </div>
    </div>
  </div>
</template>
<script>
import axios from "axios";
import qs from "qs";
import util from "@/assets/js/utils.js";
// @ is an alias to /src
import expertItem from "@/components/Expert-Item.vue";
export default {
  name: "course",
  data () {
    return {
      conditionShow: false,
      cateList: [],
      // curriculum: {
      //   curriculumName: "", //课程名称
      //   price: "", //价格
      //   chapterCount: "", //总章节
      //   category1: "", //一级类别
      //   category2: "", //二级类别
      //   category3: "", //三级类别
      //   desc: "", //简介
      //   imgUrl: '', //封面图
      // },
      cateName: "",
      cname: "", //课程名称
      cprice: "", //价格
      ccount: "", //总章节
      category1: "", //一级类别
      category2: "", //二级类别
      category3: "", //三级类别
      cdesc: "", //简介
      cimg: '', //封面图
      cimgUrl: '',//用于显示的封面图
      addShow: true,
      unitList: [],
      unitShow: false,
      curriculumId: "", //课程id
      unitAdding: false,
      unitDetail: {}
      //   name: "", //单元名称
      //   videoUrl: "", //单元视频
      //   accessoriesName: "", //单元附件名称
      //   accessoriesUrl: "" //单元附件
    };
  },
  components: {
    expertItem
  },
  created () {
    this.handleInitPage()
  },
  watch: {
    $route () {
      this.handleInitPage()
    }
  },
  computed: {
    userInfo () {
      return this.$store.state.userInfo
    }
  },
  methods: {
    handleInitPage () {
      let cid = this.$route.params.cid ? this.$route.params.cid : '';
      this.curriculumId = cid
      this.fetchClassifyList(1);
      if (cid) {
        this.fetchDetails();
        this.fetchUnitList()
      } else {
        this.cname = "" //课程名称
        this.cprice = "" //价格
        this.ccount = "" //总章节
        this.category1 = "" //一级类别
        this.category2 = "" //二级类别
        this.category3 = "" //三级类别
        this.cdesc = "" //简介
        this.cimg = '' //封面图
        this.cimgUrl = ''//用于显示的封面图
      }
    },
    handleFileChange (event) {
      //选择封面图
      this.cimg = event.target.files[0];
      this.handleFileReader('cimgUrl', event.target.files[0])
      console.log(event.target.files[0]);
    },
    handleFileChange1 (event, index) {
      //选择视频
      this.unitList[index].videoInfo = event.target.files[0];
      // this.unitList[index].videoUrl = event.target.files[0];
      console.log(this.unitList);
      console.log(event.target.files[0]);
    },
    handleFileChange2 (event, index) {
      //选择附件
      this.unitList[index].accessoriesName = event.target.files[0].name;
      this.unitList[index].accessoriesUrl = event.target.files[0];
      console.log(event.target.files[0]);
    },
    handleUploadFile (event) {
      //上传
      if (!this.cname || !this.cimg || !this.ccount) {
        alert('课程信息未填写完成！')
      }
      let that = this;
      event.preventDefault();
      let formData = new FormData();
      formData.append("id", this.curriculumId);
      formData.append("imgUrl", this.cimg);
      formData.append("curriculumName", this.cname);
      formData.append("category1", !this.category1 ? '' : this.category1);
      formData.append("category2", !this.category2 ? '' : this.category2);
      formData.append("category3", !this.category3 ? '' : this.category3);
      formData.append("price", !this.cprice ? 0 : this.cprice);
      formData.append("desc", this.cdesc);
      formData.append("chapterCount", this.ccount);
      let config = {
        headers: {
          "Content-Type": "multipart/form-data"
        }
      };
      axios
        .post("/curriculum/add", formData, config)
        .then(function (response) {
          if (response.data.suc == 200) {
            alert(that.curriculumId ? "修改成功" : "上传成功");
            that.unitShow = true;
            that.addShow = false;
            that.curriculumId = response.data.data.id;
          } else if (response.data.errCode == "ERROR_CODE_200001") {
            alert("请先审核成为专家才能发布课程");
            that.$router.push("/my/myInto");
            util.loginOver.call(that);
          } else if (response.data.errCode == "ERROR_CODE_000000") {
            util.loginOver.call(that);
          } else if (response.data.errCode == "ERROR_CODE_000002") {
            alert("参数错误");
          }
        })
        .catch(function (error) {
          console.log(error);
        });
    },
    handleUploadUnit (event, orderNum) {
      //上传单元
      let that = this;
      let index = orderNum - 1;
      event.preventDefault();
      let formData = new FormData();
      if (!this.unitList[index].id) {
        formData.append("videoUrl", this.unitList[index].videoInfo);
      } else {
        formData.append('id', this.unitList[index].id)
      }
      formData.append("curriculumId", this.curriculumId);
      formData.append("name", this.unitList[index].name);
      formData.append("accessoriesName", this.unitList[index].accessoriesName);
      formData.append("accessoriesUrl", this.unitList[index].accessoriesUrl);
      formData.append("orderNum", orderNum);
      let config = {
        headers: {
          "Content-Type": "multipart/form-data"
        }
      };
      axios
        .post("/curriculum/addUnit", formData, config)
        .then(function (response) {
          if (response.data.suc == 200) {
            alert("上传成功");
            that.unitAdding = false;
            that.unitList[index]['id'] = response.data.data.id
            that.unitList[index].videoInfo = {
              name: response.data.data.fileOName
            };
            // that.unitList[index].videoUrl = {
            //   name: response.data.data.fileOName
            // };
            that.unitList[index].addControl = false;
          } else if (response.data.errCode == "ERROR_CODE_000000") {
            util.loginOver.call(that);
          } else if (response.data.errCode == "ERROR_CODE_000002") {
            alert("参数错误");
          }
        })
        .catch(function (error) {
          console.log(error);
        });
    },
    fetchDetails () {
      // 观看某一单元(单元详情)
      let that = this
      let params = {
        curriculumId: that.curriculumId
      }
      axios
        .post('/curriculum/getUnit', qs.stringify(params))
        .then(function (response) {
          if (response.data.suc == 200) {
            if (response.data.data.isLogin) {
              let unitDetail = response.data.data
              that.cname = unitDetail.curriculum.curriculumName //课程名称
              that.cprice = unitDetail.curriculum.price //价格
              that.ccount = unitDetail.curriculum.chapterCount //总章节
              that.category1 = unitDetail.curriculum.category1 //一级类别
              that.category2 = unitDetail.curriculum.category2 //二级类别
              that.category3 = unitDetail.curriculum.category3 //三级类别
              that.cdesc = unitDetail.curriculum.desc //简介
              that.cimg = unitDetail.curriculum.imgUrl
              that.cimgUrl = 'https://kegonghui.oss-cn-beijing.aliyuncs.com/' + unitDetail.curriculum.imgUrl //封面图
            } else {
              util.loginOver.call(that)
            }
          } else if (response.data.errCode == 'ERROR_CODE_000000') {
            util.loginOver.call(that)
          }
        })
        .catch(function (error) {
          console.log(error)
        })
    },
    fetchClassifyList (level) {
      let that = this;
      axios
        .post(
          "/classify/listByJson",
          qs.stringify({
            pid: that.cateId,
            type: level > 1 ? "" : 1
          })
        )
        .then(function (response) {
          if (response.data.suc == 200) {
            that.cateList = response.data.data;
          } else if (response.data.errCode == "ERROR_CODE_000000") {
            util.loginOver.call(that);
          }
        })
        .catch(function (error) {
          console.log(error);
        });
    },
    fetchUnitList () {
      //如果有id，获取单元列表
      let that = this;
      axios
        .post(
          "/curriculum/unitList",
          qs.stringify({
            id: this.curriculumId
          })
        )
        .then(function (response) {
          if (response.data.suc == 200) {
            that.unitList = response.data.data;
          } else if (response.data.errCode == "ERROR_CODE_000000") {
            util.loginOver.call(that);
          }
        })
        .catch(function (error) {
          console.log(error);
        });
    },
    handlePriceChange (e) {
      console.log(e);
      // this.price='';
    },
    handleCateSelect (name, id1, id2 = "", id3 = "") {
      this.cateName = name;
      this.category1 = id1;
      this.category2 = id2;
      this.category3 = id3;
    },
    handleAddUnit () {
      if (this.unitAdding) {
        alert("有新单元正在操作");
        return false;
      }
      this.unitList.push({
        name: "",
        videoInfo: {},
        videoUrl: "", //单元视频
        accessoriesName: "", //单元附件名称
        accessoriesUrl: "", //单元附件
        addControl: true
      });
      this.unitAdding = true;
    },
    handleDeleteUnit (index) {
      let id = this.unitList[index].id;
      if (id) {
        if (confirm("确认删除这个单元？")) {
          let that = this;
          axios
            .post(
              "/curriculum/deleteUnit",
              qs.stringify({
                id: id
              })
            )
            .then(function (response) {
              if (response.data.suc == 200) {
                that.unitList.splice(index, 1);
              } else if (response.data.errCode == "ERROR_CODE_000000") {
                util.loginOver.call(that);
              } else if (response.data.errCode == "ERROR_CODE_000002") {
                alert("参数错误");
              }
            })
            .catch(function (error) {
              console.log(error);
            });
        }
      } else {
        this.unitList.splice(index, 1);
      }
    },
    handleFileReader (data, file) {
      // 前端展示图片
      let that = this
      var reader = new FileReader()
      // 将文件以Data URL形式进行读入页面
      reader.addEventListener(
        'load',
        function () {
          that[data] = reader.result
          // that.baseImg = reader.result
        },
        false
      )
      // 调用reader.readAsDataURL()方法，把图片转成base64
      reader.readAsDataURL(file)
    },
  }
};
</script>
<style lang="scss" scoped>
.radio-inline {
  margin-top: 35px;
  color: #0092dc !important;
}
.dropdown-submenu {
  & > li {
    display: block;
  }
}
// .thumbnail {
//   position: relative;
// }
.add-unit-btn {
  padding: 20px 0px;
}
// .unit-item {
//   margin-top: 20px;
// }
</style>
